<!--
*@Author: zt
*@Description: 功能管理
*@Date: 2024-08-14
-->
<template>
  <a-layout class="f-h-100">
    <u-collapsed-sider class="f-padding-6">
      <u-tree :treeData="treeData" ref="treeRef" :field-names="{
        title: 'name',
        key: 'keyid',
        children: 'children',
      }" 
      :showSearch="false"
      v-model:expandedKeys="treeExpandes" @select="treeClick" />
    </u-collapsed-sider>
    <a-layout-content class="s-bg-white" style="margin-left: 12px; padding: 12px">
      <a-layout class="f-h-100">
        <a-layout-header class="f-h-auto" style="padding: 0 0 12px; line-height: unset; background: #fff">
          <a-space>
            <u-icon-button itype="add" @click="addBtn">新增子级</u-icon-button>
            <u-icon-button itype="save" @click="submit">保存</u-icon-button>
            <u-icon-button itype="delete" @click="deleteBtn">删除</u-icon-button>
          </a-space>
        </a-layout-header>
        <a-layout-content class="s-bg-white" style="padding: 0">
          <u-loading-box :spinning="loading">
            <u-form :elements="elements" :model="form" ref="formRef" v-bind="$attrs" />
          </u-loading-box>
        </a-layout-content>
      </a-layout>
    </a-layout-content>
  </a-layout>
</template>
<script lang="ts" setup>
import * as menuService from "@/service/system/menu/index";
import { isSel } from "@/common/model/base";
import { disableTreeKeyid } from "@/util/format.ts"
import { alertC, isValue, nullC } from "@/util/common";
import { computed, onMounted, reactive, ref } from "vue";
import { headerMenuTypes } from '@/common/model/const';

const baseForm = ref({});
let treeCurrentData = reactive({});
const treeData = ref([]);
const treeExpandes = ref([]);
const loading = ref(false);

let form = reactive<any>({
  isuse: "1",
  fkparentid: "",
  name: "",
  keyid: "",
  code: "",
  modpath: "",
  iconurl: "",
  isdisplay: "",
  remark: "",
});

let elements = reactive<any>([
  {
    element: "treeselect",
    label: "父级",
    col: { span: 24 },
    key: "fkparentid",
    formItemProps: { labelWidth: "150px" },
    componentProps: {
      treeData: computed(() => treeData.value),
      fieldNames: {
        label: "name", value: "keyid", children: 'children',
      },
      required: true,
    },
  },
  {
    element: "input",
    label: "功能模块名称",
    col: { span: 24 },
    key: "name",
    formItemProps: { labelWidth: "150px" },
    componentProps: {
      required: true,
      maxlength: 50,
      showCount: true,
    },
  },
  {
    element: "input",
    label: "功能模块代码",
    col: { span: 12 },
    key: "code",
    formItemProps: { labelWidth: "150px" },
    componentProps: {
      required: true,
      precision: 0,
    },
  },
  {
    element: "input",
    label: "页面路径",
    col: { span: 12 },
    key: "modpath",
    formItemProps: { labelWidth: "150px" },
  },
  {
    element: "select",
    label: "是否使用",
    col: { span: 12 },
    key: "isuse",
    formItemProps: { labelWidth: "150px" },
    componentProps: {
      options: isSel(),
      required: true,
    },
  },
  {
    element: "input",
    label: "图标",
    col: { span: 12 },
    key: "iconurl",
    formItemProps: { labelWidth: "150px" },
  },
  {
    element: "select",
    label: "是否显示在导航栏中",
    col: { span: 12 },
    key: "isdisplay",
    formItemProps: { labelWidth: "150px" },
    componentProps: {
      options: isSel(),
      required: true,
    },
  },
  {
    element: "select",
    label: "菜单类型",
    col: { span: 12 },
    key: "menutypes",
    formItemProps: { labelWidth: "150px" },
    componentProps: {
      options: headerMenuTypes,
      required: true,
    },
  },
  {
    element: "textarea",
    label: "备注",
    col: { span: 24 },
    key: "remark",
    formItemProps: { labelWidth: "150px" },
    componentProps: {
      maxlength: 200,
      showCount: true,
    },
  },
]);

onMounted(() => {
  getTree("init");
});

// 获取树形
// type = init 为初次进入时的加载
const getTree = (type?: string) => {
  return menuService
    .menutree("")
    .then((res) => {
      if (res.code == 0 && res.data) {
        treeData.value.splice(0, treeData.value.length, ...res.data);
        elements.splice(0, 1, { ...elements[0], data: res.data });
        if (treeData.value.length != 0 && type == "init") {
          treeExpandes.value.splice(
            0,
            treeExpandes.value.length,
            treeData.value[0]["keyid"]
          );
        }
      }
    })
    .catch(() => { });
};

const formRef = ref();
// 保存
const submit = () => {
  if (!treeCurrentData["keyid"]) {
    alertC("请先在左侧选择节点!");
    return;
  }

  formRef.value.form.validate().then((vali) => {
    if (!vali) {
      alertC("请先将必填字段填写完毕!");
      return;
    }

    const url = form.keyid ? "update" : "add";

    loading.value = true;
    menuService[url](form)
      .then(async (res) => {
        loading.value = false;
        if (res.code == 0) {
          // setParentIdDis(false);
          alertC(res.msg, "success");
          // 赋值表单
          if (res.data) {
            for (let key in form) {
              if (isValue(res.data[key])) {
                form[key] = nullC(res.data[key]);
                // this.$set(this.form, key, this.$common.nullC(res.data.data[key]))
              }
            }
            treeCurrentData = res.data;
          }
          form.isuse = nullC(form.isuse) + "";
          form.isdisplay = nullC(form.isdisplay) + "";

          // 获取树形数据 并 定位树节点
          await getTree();
          treeExpandes.value.splice(
            0,
            treeExpandes.value.length,
            form["keyid"]
          );
        } else {
          alertC(res.msg, "warning");
        }
      })
      .catch((err) => {
        loading.value = false;
      });
  });
};

// 侧边树形点击
const treeClick = (keys, { selectedNodes, node }) => {
  formRef.value.form.resetFields();
  // setParentIdDis(false);
  clearValidate();
  treeCurrentData = node.dataRef;
  form.keyid = keys["keyid"];
  loading.value = true;
  menuService
    .singleQuery(treeCurrentData["keyid"])
    .then((res) => {
      loading.value = false;
      if (res.code == 0) {
        for (let key in form) {
          if (isValue(res.data[key])) {
            form[key] = res.data[key]
            // this.$set(this.form, key, this.$common.nullC(res.data.data[key]))
          }
        }

        form.isuse = nullC(form.isuse) + "";
        form.isdisplay = nullC(form.isdisplay) + "";
        clearValidate();
      }

      elements.splice(0, 1, {
        ...elements[0],
        data: disableTreeKeyid(
          JSON.parse(JSON.stringify(treeData.value)),
          keys["keyid"]
        ),
      });
    })
    .catch(() => (loading.value = false));
};

// 删除
const deleteBtn = () => {
  if (!isValue(treeCurrentData["keyid"])) {
    alertC("请选择要删除的节点!");
    return;
  }

  // 顶级节点不能删除
  if (treeCurrentData["fkparentid"] == 0) {
    alertC("不能删除顶级节点!");
    return;
  }

  clearValidate();

  // 确认删除
  loading.value = true;
  menuService
    .del({ ids: treeCurrentData["keyid"] })
    .then((res) => {
      loading.value = false;
      if (res.code == 0) {
        getTree("init");

        // 清除选中的数据
        treeCurrentData = {};
        formRef.value.form.resetFields();

        form.keyid = "";
        form.fkparentid = "";

        alertC(res.msg, "success");
      } else {
        alertC(res.msg, "warning");
      }
    })
    .catch((err) => {
      loading.value = false;
    });
  //  confirmC({ msg: "确认删除选中节点？",  }).then(() => {

  //   })
  //   .catch(() => {})
};

// 新增子级
const addBtn = () => {
  if (!isValue(treeCurrentData["keyid"])) {
    alertC("请先在左侧选择节点!");
    return;
  }
  // form = {};
  form.fkparentid = form.keyid;
  form.keyid = '',
    form.code = '',
    form.name = '',
    form.modpath = '',
    form.remark = '',
    form.iconurl = '',


    form["isuse"] = "1";
  form["isdisplay"] = "1";
  // this.$set(this.form, 'fkparentid', this.treeCurrentData['keyid']);
  // this.$set(this.form, 'isuse', '1');
  // this.$set(this.form, 'isdisplay', '1');
  form.keyid = "";

  // setParentIdDis(true);

  // clearValidate();
};

// 清除已有的表单验证结果
const clearValidate = () => {
  formRef.value.form.clearValidate();
};

// 禁用父级选择框
// const setParentIdDis = (disabled) => {
//   let index = elements.findIndex((item) => item.key == "fkparentid");
//   let formItem = elements[index];
//   formItem.componentProps.disabled = disabled;
//   elements.splice(index, 1, { ...formItem });
// };
</script>
<style lang="scss"></style>
